﻿using SHDocVw;
using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.domain.constant;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;
using SUNRPA.CONTROLS.IMPL.util;
using System.Collections.Concurrent;

namespace SUNRPA.CONTROLS.IMPL.controls {
    /// <summary>
    /// 对于打开网页的超时错误处理暂时都没有做，之后在完善
    /// </summary>
    public class GetOpenedWebObjNAction:BaseControlActions {
        public override int Execute(int currentIndex, FlowItem item, ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> globleData, List<FlowItem> flowItems) {
            GetOpenedWebObjNParam? param = item.ControlParam as GetOpenedWebObjNParam;
            BrowserType browserType = param.BrowType;
            string matchContent = param.MatchContent;
            this.GetStringVar(ref matchContent, globleData);
            string saveVarName = param.OutVarName;
            this.GetStringVar(ref saveVarName, globleData);
            int matchType = param.MatchType;

            BrowserUtil browserUtil;
            WebPage webPage;
            switch (browserType) { 
                case BrowserType.GOOGLE:
                    NamePipeRequest request = new NamePipeRequest(DefaultContents.GET_OPENED_WEBPAGE,
                        new Dictionary<string, object> { { "matchType", matchType }, { "matchContent", matchContent} });
                    BridgeResponse resp = NamedPipeClientUtil.SendRequestV1(request);
                    if(!resp.code.Equals(CommunicationCode.OK)) { 
                        throw new RpaRuntimeException(resp.msg);
                    }
                    webPage = WebPage.CreateChromeWebPage(int.Parse(resp.result.ToString()));
                    webPage.VarName = saveVarName;
                    this.saveVar(globleData, saveVarName, webPage, DefaultContents.RUNNING_PARAM);
                    break;
                case BrowserType.IE:
                    break;
                case BrowserType.EDGE:
                    break;
                default:
                    throw new RpaRuntimeException("浏览器类型错误");
            }
            return currentIndex;
        }
    }
}
